package com.ykq.predicate;

import lombok.Data;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.BetweenRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import javax.validation.constraints.NotNull;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {

    public AgeRoutePredicateFactory() {
        super(AgeRoutePredicateFactory.Config.class);
    }
    public List<String> shortcutFieldOrder() { //读取application中的内容 并赋值给Config中两个属性
        return Arrays.asList("minAge", "maxAge");
    }
    //核心代码
    public Predicate<ServerWebExchange> apply(AgeRoutePredicateFactory.Config config) {
        return new GatewayPredicate() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                //我如何获取请求路径中含的参数age
                String queryAge=serverWebExchange.getRequest().getQueryParams().getFirst("age");
                if(queryAge==null){
                    return false;
                }else{
                    try {
                        int age = Integer.parseInt(queryAge);
                        if(age>=config.minAge&&age<=config.maxAge){
                            return true;
                        }else{
                            return false;
                        }
                    }catch (Exception e){
                        return false;
                    }
                }

            }
        };
    }

    @Validated
    @Data
    public static class Config {
        @NotNull
        private Integer minAge;
        @NotNull
        private Integer maxAge;
        public Config() {
        }
    }


}
